package com.pfzy.lib.net.utils;

import com.pfzy.lib.sdk.utils.base64.Base64Util;
import com.pfzy.lib.sdk.utils.base64.MyBase64;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * RSA加、解密算法工具类
 */
public class RsaUtil {
    /**
     * 加密算法AES
     */
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * 算法名称/加密模式/数据填充方式
     * 默认：RSA/ECB/PKCS1Padding
     */
    private static final String ALGORITHMS = "RSA/ECB/PKCS1Padding";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 256;
    /**
     * RSA 位数 如果采用2048 上面最大加密和最大解密则须填写:  245 256
     */
    private static final int INITIALIZE_LENGTH = 2048;
    /**
     * 后端RSA的密钥对(公钥和私钥)Map，由静态代码块赋值
     */
    private static Map<String, Object> genKeyPair = new HashMap<>();

    private static String PRIVATE_KEY = "";
    private static String PUBLIC_KEY = "";

    static {
        try {
            genKeyPair.putAll(genKeyPair());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成密钥对(公钥和私钥)
     */
    private static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(INITIALIZE_LENGTH);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        //公钥
        keyMap.put(PUBLIC_KEY, publicKey);
        //私钥
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 私钥解密
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     */
    public static String decryptByPrivateKey(String encryptedData, String privateKey) throws Exception {
        //base64格式的key字符串转Key对象
        byte[] bytes = encryptedData.getBytes(CHARSET_UTF8);
        byte[] keyBytes = MyBase64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(ALGORITHMS, new BouncyCastleProvider());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        byte[] sign = cipher.doFinal(MyBase64.decodeBase64(bytes));
        String signVal = MyBase64.encodeBase64String(sign);
        String strus = Base64Util.decode(signVal, "utf-8");
        //分段进行解密操作
        return strus;
    }

    public static final Charset CHARSET_UTF8 = StandardCharsets.UTF_8;

    /**
     * 用公钥对字符串进行加密
     *
     * @param data 原文
     */
    public static String encryptByPublicKey(String data, String publicKey) throws Exception {
        // 得到公钥
        byte[] keyBytes = MyBase64.decodeBase64(publicKey);
        byte[] bytes = data.getBytes(CHARSET_UTF8);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey keyPublic = kf.generatePublic(keySpec);
        // 加密数据
        Cipher cp = Cipher.getInstance(ALGORITHMS);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        byte[] sign = cp.doFinal(bytes);
        String signVal = MyBase64.encodeBase64String(sign);
        return signVal;
    }

    @SuppressWarnings("unchecked")
    public static <T> T byteArrayToObject(byte[] value, Class<T> clazz) {
        ObjectInputStream objectInputStream;
        try {
            objectInputStream = new ObjectInputStream(new ByteArrayInputStream(value));
            return (T) objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取私钥
     */
    public static String getPrivateKey() {
        Key key = (Key) genKeyPair.get(PRIVATE_KEY);
        return MyBase64.encodeBase64String(key.getEncoded());
    }
    public static void setPrivateKey(String key){
        PRIVATE_KEY = key;
    }

    /**
     * 获取公钥
     */
    public static String getPublicKey() {
        Key key = (Key) genKeyPair.get(PUBLIC_KEY);
        return MyBase64.encodeBase64String(key.getEncoded());
    }
    public static void setPublicKey(String key){
        PUBLIC_KEY = key;
    }

    /**
     * 分段进行加密、解密操作
     */
    private static byte[] encryptAndDecryptOfSubsection(byte[] data, Cipher cipher, int encryptBlock) throws Exception {
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > encryptBlock) {
                cache = cipher.doFinal(data, offSet, encryptBlock);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * encryptBlock;
        }
        byte[] toByteArray = out.toByteArray();

        out.close();
        return toByteArray;
    }
}


